package org.mobile.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mobile.beans.Phone;

/**
 * Servlet implementation class AddToCart
 */
@WebServlet("/addToCart")
public class AddToCart extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddToCart() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int index= Integer.parseInt(request.getParameter("index"));
		List<Phone> phoneList= (List<Phone>)request.getSession().getAttribute("phones");
		List<Phone> cart= (List<Phone>)request.getSession().getAttribute("cart");
		if(phoneList != null){
			Phone selectedPhone= phoneList.get(index);
			if(cart == null)
				cart= new ArrayList<Phone>();
			cart.add(selectedPhone);
			request.getSession().setAttribute("cart", cart);
			response.sendRedirect("index.jsp");
		}
		else{
			request.setAttribute("error", "Błąd dodawania do koszyka!");
			request.getRequestDispatcher("errPage.jsp").forward(request, response);
		}
	}

}
